<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="单据号" prop="billsID">
        <el-input
          v-model="queryParams.billsID"
          placeholder="请输入单据号"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次号" prop="drugBatchNo">
        <el-input
          v-model="queryParams.drugBatchNo"
          placeholder="请输入批次号"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="药品名称" prop="drugName">
        <el-input
          v-model="queryParams.drugName"
          placeholder="请输入药品名称"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据类型" prop="billsType">
        <el-cascader
          v-model="selectedBillsType"
          :options="billsTypeOptions"
          :props="{
            value: 'value',
            label: 'label',
            children: 'children',
            emitPath: false
          }"
          placeholder="请选择单据类型"
          clearable
          style="width: 250px"
          @change="handleBillsTypeChange"
        />
      </el-form-item>
      <el-form-item label="上传状态" prop="uploadState">
        <el-select
          v-model="queryParams.uploadState"
          placeholder="请选择上传状态"
          clearable
          style="width: 150px"
        >
          <el-option label="未上传" value="0" />
          <el-option label="上传成功" value="1" />
          <el-option label="上传失败" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="往来单位" prop="billsCD">
        <el-input
          v-model="queryParams.billsCD"
          placeholder="请输入往来单位"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
        <el-switch style="margin-left: 10px;" v-model="queryParams.modeCode" active-text="精准查询" inactive-text="模糊查询" :active-value="1"
                   :inactive-value="0">
        </el-switch>
      </el-form-item>
      <el-form-item label="确认时间" prop="checkDateRange">
        <el-date-picker
          v-model="checkDateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
          style="width: 350px"
          @change="handleCheckDateRangeChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wareHouse:list:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown
          @command="handleExportCommand"
          v-hasPermi="['wareHouse:list:export']"
          trigger="click"
        >
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
          >
            导出数据<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
<!--            <el-dropdown-item command="exportAll" :disabled="total > 200">-->
<!--              <i class="el-icon-document-copy"></i> 导出全部数据-->
<!--              <span v-if="total <= 200" style="color: #909399; font-size: 12px; margin-left: 8px;">-->
<!--                ({{ total || 0 }}条)-->
<!--              </span>-->
<!--              <span v-else style="color: #f56c6c; font-size: 12px; margin-left: 8px;">-->
<!--                ({{ total }}条，超出限制)-->
<!--              </span>-->
<!--            </el-dropdown-item>-->
            <el-dropdown-item
              command="exportSelected"
              :disabled="multiple || ids.length > 20"
              :class="{ 'is-disabled': multiple || ids.length > 20 }"
            >
              <i class="el-icon-s-check"></i> 导出选中数据
              <span v-if="!multiple && ids.length <= 20" style="color: #909399; font-size: 12px; margin-left: 8px;">
                ({{ ids.length }}个单据)
              </span>
              <span v-else-if="!multiple && ids.length > 20" style="color: #f56c6c; font-size: 12px; margin-left: 8px;">
                ({{ ids.length }}个单据，超出限制)
              </span>
              <span v-else style="color: #c0c4cc; font-size: 12px; margin-left: 8px;">
                (请先选择)
              </span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 功能提示 -->
    <el-alert
      title="提示：选中任意一条记录时，相同单据号的所有记录会自动联动选择。相同单据号的记录用相同颜色的左边框标识。"
      type="info"
      :closable="false"
      show-icon
      style="margin-bottom: 10px;">
    </el-alert>

    <el-table
      v-loading="loading"
      :data="ListList"
      @selection-change="handleSelectionChange"
      @select="handleSelect"
      @select-all="handleSelectAll"
      ref="multipleTable"
      border
      stripe
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      :row-class-name="getRowClassName"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据号" align="center" prop="billsID" min-width="180" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="bills-id-text">{{ scope.row.billsID }}</span>
        </template>
      </el-table-column>
      <el-table-column label="批次号" align="center" prop="drugBatchNo" min-width="150" show-overflow-tooltip />
      <el-table-column label="药品名称" align="center" prop="drugName" min-width="200" show-overflow-tooltip />
      <el-table-column label="单据类型" align="center" prop="billsType" width="120">
        <template slot-scope="scope">
          <el-tag
            :type="getBillsTypeTagType(scope.row.billsType)"
            size="small"
          >
            {{ scope.row.billsName || scope.row.billsType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="往来单位" align="center" prop="billsCD" min-width="200" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.billsCD || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="上传状态" align="center" prop="uploadState" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="getUploadStateTagType(scope.row.uploadState)"
            size="small"
          >
            {{ getUploadStateText(scope.row.uploadState) }}
          </el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column label="配送单位" align="center" prop="senderId" min-width="120" show-overflow-tooltip>-->
<!--        <template slot-scope="scope">-->
<!--          {{ scope.row.senderId || '-' }}-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="委托单位" align="center" prop="ownerID" min-width="120" show-overflow-tooltip>-->
<!--        <template slot-scope="scope">-->
<!--          {{ scope.row.ownerID || '-' }}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="确认时间" align="center" prop="checkDate" width="150">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.checkDate) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="420">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleBatchNumberMaintenance(scope.row)"
            v-hasPermi="['wareHouse:list:update']"
          >批次维护</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewDetail(scope.row)"
            v-hasPermi="['wareHouse:list:query']"
          >查看明细</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-upload"-->
<!--            @click="handleUpload(scope.row)"-->
<!--            v-hasPermi="['wareHouse:list:edit']"-->
<!--            :disabled="scope.row.uploadState === '1'"-->
<!--          >上传</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wareHouse:list:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 医疗机构选择对话框 -->
    <el-dialog title="选择医疗机构" :visible.sync="medicalInstitutionDialogVisible" width="600px" append-to-body>
      <el-form :model="uploadForm" label-width="120px">
        <el-form-item label="医疗机构名称" prop="institutionName">
          <el-select
            v-model="selectedInstitution"
            filterable
            clearable
            placeholder="请选择医疗机构"
            style="width: 100%"
            @change="handleInstitutionChange">
            <el-option
              v-for="item in medicalInstitutionsList"
              :key="item.institutionId"
              :label="item.institutionName"
              :value="item.institutionId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医疗机构代码" prop="institutionId">
          <el-input v-model="uploadForm.institutionId" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="medicalInstitutionDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmUpload">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 批次号维护对话框 -->
    <el-dialog title="批次维护" :visible.sync="batchNumberDialogVisible" width="1000px" append-to-body>
      <div class="batch-maintenance-container">
        <div class="header-info">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="单据号">{{ currentBillsInfo.billsID }}</el-descriptions-item>
            <el-descriptions-item label="单据类型">{{ currentBillsInfo.billsName || currentBillsInfo.billsType }}</el-descriptions-item>
            <el-descriptions-item label="往来单位">{{ currentBillsInfo.billsCD || '-' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <el-table
          v-loading="detailLoading"
          :data="detailList"
          border
          stripe
          style="margin-top: 20px;"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column label="药品编码" align="center" prop="drugID" min-width="120" show-overflow-tooltip />
          <el-table-column label="药品名称" align="center" min-width="200">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.drugName"
                placeholder="请输入药品名称"
                size="small"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column label="规格" align="center" prop="specification" min-width="120" show-overflow-tooltip />
          <el-table-column label="单位" align="center" prop="unit" width="80" />
          <el-table-column label="数量" align="center" prop="quantity" width="80" />
          <el-table-column label="批次号" align="center" min-width="160">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.batchNumber"
                placeholder="请输入批次号"
                size="small"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column label="生产日期" align="center" min-width="150">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.productionDate"
                type="date"
                placeholder="选择生产日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                size="small"
                style="width: 100%;"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column label="有效期" align="center" min-width="150">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.validityPeriod"
                type="date"
                placeholder="选择有效期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                size="small"
                style="width: 100%;"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" min-width="180">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.remark"
                placeholder="请输入备注"
                size="small"
                clearable
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchNumberDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmBatchNumberUpdate" :loading="updateLoading">保存修改</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style scoped>
/* 导出下拉菜单样式 */
::v-deep .el-dropdown-menu__item {
  padding: 8px 16px;
  line-height: 1.5;
}

::v-deep .el-dropdown-menu__item.is-disabled {
  color: #c0c4cc !important;
  cursor: not-allowed;
  background-color: #f5f5f5;
}

::v-deep .el-dropdown-menu__item.is-disabled:hover {
  background-color: #f5f5f5 !important;
  color: #c0c4cc !important;
}

::v-deep .el-dropdown-menu__item:not(.is-disabled):hover {
  background-color: #f5f7fa;
  color: #409eff;
}

/* 表格样式优化 */
::v-deep .el-table .el-table__row:hover {
  background-color: #f8f9ff;
}

::v-deep .el-table .el-table__header-wrapper th {
  background-color: #f5f7fa !important;
  color: #606266 !important;
  font-weight: 600;
}

/* 查询表单样式优化 */
::v-deep .el-form--inline .el-form-item {
  margin-bottom: 10px;
}

/* 表格样式优化 */
::v-deep .el-table th {
  font-weight: 600;
}

::v-deep .el-table .cell {
  padding: 0 8px;
}

/* 操作按钮样式 */
::v-deep .el-button--text {
  padding: 0;
  margin-right: 8px;
}

::v-deep .el-button--text:last-child {
  margin-right: 0;
}

/* 状态标签样式 */
::v-deep .el-tag--small {
  height: 24px;
  line-height: 22px;
}

/* 批次号维护对话框样式 */
.batch-maintenance-container {
  padding: 10px 0;
}

.header-info {
  margin-bottom: 20px;
}

::v-deep .el-descriptions__label {
  font-weight: 600;
  color: #606266;
}

::v-deep .el-descriptions__content {
  color: #303133;
}

/* 批次号维护表格样式 */
::v-deep .batch-maintenance-container .el-table th {
  background-color: #f5f7fa !important;
  color: #606266 !important;
  font-weight: 600;
}

::v-deep .batch-maintenance-container .el-table .el-input__inner {
  border-radius: 4px;
}

::v-deep .batch-maintenance-container .el-table .el-input__inner:focus {
  border-color: #409eff;
}

/* 确保输入框可以正常输入 */
::v-deep .batch-maintenance-container .el-input {
  pointer-events: auto !important;
}

::v-deep .batch-maintenance-container .el-input__inner {
  pointer-events: auto !important;
  user-select: text !important;
  -webkit-user-select: text !important;
  -moz-user-select: text !important;
  -ms-user-select: text !important;
}

::v-deep .batch-maintenance-container .el-table .cell {
  pointer-events: auto !important;
}

/* 确保表格行可以正常交互 */
::v-deep .batch-maintenance-container .el-table__row {
  pointer-events: auto !important;
}

/* 单据号文本样式 */
.bills-id-text {
  color: #409EFF;
  font-weight: 500;
}

/* 相同单据号行的样式 - 使用不同的左边框颜色来区分 */
::v-deep .el-table .bills-group-0 {
  border-left: 3px solid #409EFF;
}
::v-deep .el-table .bills-group-1 {
  border-left: 3px solid #67C23A;
}
::v-deep .el-table .bills-group-2 {
  border-left: 3px solid #E6A23C;
}
::v-deep .el-table .bills-group-3 {
  border-left: 3px solid #F56C6C;
}
::v-deep .el-table .bills-group-4 {
  border-left: 3px solid #909399;
}
::v-deep .el-table .bills-group-5 {
  border-left: 3px solid #9C27B0;
}
::v-deep .el-table .bills-group-6 {
  border-left: 3px solid #FF9800;
}
::v-deep .el-table .bills-group-7 {
  border-left: 3px solid #4CAF50;
}
::v-deep .el-table .bills-group-8 {
  border-left: 3px solid #2196F3;
}
::v-deep .el-table .bills-group-9 {
  border-left: 3px solid #795548;
}
</style>

<script>
import { listBillsDetail, delList, uploadBills, getBillsDetailList, updateDetailBatchNumber } from "@/api/wareHouse/list";
import { listMedicalInstitutions } from "@/api/hospital/MedicalInstitutions";

export default {
  name: "List",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单据主表表格数据
      ListList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        billsID: null,
        drugBatchNo: null,
        drugName: null,
        userID: null,
        billsType: null,
        billsCD: null,
        uploadState: null,
        billsCheck: null,
        senderId: null,
        ownerID: null,
        remarks1: null,
        remarks2: null,
        billsFlag: null,
        checkDate: null,
        checkDateStart: null,
        checkDateEnd: null,
        modeCode:0
      },
      // 确认时间范围
      checkDateRange: null,
      // 选中的单据类型
      selectedBillsType: null,
      // 单据类型选项（二级菜单）
      billsTypeOptions: [
        {
          value: 'WareHouseIn',
          label: '入库',
          children: [
            { value: 'PurchaseWareHouseIn', label: '采购入库' },
            { value: 'ProduceWareHouseIn', label: '生产入库' },
            { value: 'ReturnWareHouseIn', label: '退货入库' },
            { value: 'AllocateWareHouseIn', label: '调拨入库' },
            { value: 'GiftWareHouseIn', label: '赠品入库' },
            { value: 'OtherWareHouseIn', label: '其他入库' }
          ]
        },
        {
          value: 'WareHouseOut',
          label: '出库',
          children: [
            { value: 'SalesWareHouseOut', label: '销售出库' },
            { value: '201', label: '销售出库(201)' },
            { value: 'ReturnWareHouseOut', label: '退货出库' },
            { value: 'AllocateWareHouseOut', label: '调拨出库' },
            { value: 'ReworkWareHouseOut', label: '返工出库' },
            { value: 'DestoryWareHouseOut', label: '销毁出库' },
            { value: 'InspectionWareHouseOut', label: '抽检出库' },
            { value: 'DirectWareHouseOut', label: '直调出库' },
            { value: 'GiftWareHouseOut', label: '赠品出库' },
            { value: 'OtherWareHouseOut', label: '其他出库' },
            { value: 'RetailWareHouseOut', label: '使用出库' }
          ]
        }
      ],
      // 单据类型颜色映射（基于billsType）
      billsTypeColorMap: {
        // 入库类型 - 绿色
        'PurchaseWareHouseIn': 'success',
        'ProduceWareHouseIn': 'success',
        'ReturnWareHouseIn': 'success',
        'AllocateWareHouseIn': 'success',
        'GiftWareHouseIn': 'success',
        'OtherWareHouseIn': 'success',
        // 出库类型 - 红色
        'SalesWareHouseOut': 'danger',
        'ReturnWareHouseOut': 'danger',
        'AllocateWareHouseOut': 'danger',
        'ReworkWareHouseOut': 'danger',
        'DestoryWareHouseOut': 'danger',
        'InspectionWareHouseOut': 'danger',
        'DirectWareHouseOut': 'danger',
        'GiftWareHouseOut': 'danger',
        'OtherWareHouseOut': 'danger',
        'RetailWareHouseOut': 'danger',
        // 数字类型映射
        '201': 'danger'
      },
      // 医疗机构对话框显示状态
      medicalInstitutionDialogVisible: false,
      // 医疗机构列表
      medicalInstitutionsList: [],
      // 选中的医疗机构
      selectedInstitution: null,
      // 上传表单
      uploadForm: {
        billsID: null,
        institutionId: '',
        institutionName: ''
      },
      // 当前操作的行数据
      currentRow: null,
      // 批次号维护对话框显示状态
      batchNumberDialogVisible: false,
      // 当前单据信息
      currentBillsInfo: {},
      // 明细列表
      detailList: [],
      // 明细加载状态
      detailLoading: true,
      // 更新加载状态
      updateLoading: false,
      // 测试输入框
      testInput: '',
      // 测试输入框2
      testInput2: '',
      // 防止递归调用的标志
      isUpdatingSelection: false
    };
  },
  created() {
    this.getList();
    this.getMedicalInstitutions();
  },
  methods: {
    /** 查询单据主表列表 */
    getList() {
      this.loading = true;
      // 使用新的批次号查询接口
      listBillsDetail(this.queryParams).then(response => {
        console.log('API Response:', response); // 调试日志
        this.ListList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch(error => {
        console.error('获取列表数据失败:', error);
        this.loading = false;
        this.$modal.msgError("获取列表数据失败");
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.checkDateRange = null;
      this.queryParams.checkDateStart = null;
      this.queryParams.checkDateEnd = null;
      this.handleQuery();
    },

    /** 处理确认时间范围变化 */
    handleCheckDateRangeChange(value) {
      if (value && value.length === 2) {
        this.queryParams.checkDateStart = value[0];
        this.queryParams.checkDateEnd = value[1];
      } else {
        this.queryParams.checkDateStart = null;
        this.queryParams.checkDateEnd = null;
      }
    },
    // 单行选择事件 - 实现联动选择
    handleSelect(selection, row) {
      // 防止递归调用
      if (this.isUpdatingSelection) {
        return;
      }

      this.isUpdatingSelection = true;

      // 判断当前行是被选中还是取消选中
      const isSelected = selection.includes(row);

      // 找到相同单据号的所有行
      const sameBillsRows = this.ListList.filter(item => item.billsID === row.billsID);

      // 对相同单据号的所有行执行相同的选择操作
      sameBillsRows.forEach(sameRow => {
        if (isSelected) {
          // 如果当前行被选中，则选中所有相同单据号的行
          if (!selection.includes(sameRow)) {
            this.$refs.multipleTable.toggleRowSelection(sameRow, true);
          }
        } else {
          // 如果当前行被取消选中，则取消选中所有相同单据号的行
          this.$refs.multipleTable.toggleRowSelection(sameRow, false);
        }
      });

      this.isUpdatingSelection = false;
    },

    // 全选事件
    handleSelectAll(selection) {
      // 全选时不需要特殊处理，保持默认行为
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      // 对单据号进行去重，因为同一个单据可能有多个批次/药品
      const uniqueBillsIDs = [...new Set(selection.map(item => item.billsID))];
      this.ids = uniqueBillsIDs;
      this.single = uniqueBillsIDs.length !== 1;
      this.multiple = !uniqueBillsIDs.length;

      // 显示选中信息
      if (uniqueBillsIDs.length > 0) {
        const selectedCount = selection.length;
        const uniqueCount = uniqueBillsIDs.length;
        if (selectedCount !== uniqueCount) {
          console.log(`选中了 ${selectedCount} 条记录，包含 ${uniqueCount} 个不同的单据号`);
        }
      }
    },

    // 获取行样式类名
    getRowClassName({ row, rowIndex }) {
      // 为相同单据号的行添加相同的类名，便于视觉识别
      const billsID = row.billsID;
      if (billsID) {
        // 使用单据号的哈希值来生成类名，确保相同单据号有相同样式
        const hash = this.hashCode(billsID);
        return `bills-group-${Math.abs(hash) % 10}`;
      }
      return '';
    },

    // 简单的哈希函数
    hashCode(str) {
      let hash = 0;
      for (let i = 0; i < str.length; i++) {
        const char = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash; // 转换为32位整数
      }
      return hash;
    },

    /** 查看明细按钮操作 */
    handleViewDetail(row) {
      const billsID = row.billsID;
      console.log('查看明细 - 单据号:', billsID);
      console.log('跳转路径:', '/wareHouse/list-detail/detail');
      this.$router.push({
        path: '/wareHouse/list-detail/detail',
        query: { billsID: billsID }
      });
    },


    /** 删除按钮操作 */
    handleDelete(row) {
      const billsIDs = row ? [row.billsID] : this.ids;
      const billsIDsText = Array.isArray(billsIDs) ? billsIDs.join(", ") : billsIDs;
      const countText = row ? '该单据' : `选中的 ${billsIDs.length} 个单据`;
      this.$modal.confirm(`是否确认删除${countText}？\n\n单据号：${billsIDsText}\n\n注意：删除后无法恢复！`).then(() => {
        return delList(billsIDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 导出命令处理 */
    handleExportCommand(command) {
      if (command === 'exportAll') {
        this.handleExportAll();
      } else if (command === 'exportSelected') {
        this.handleExportSelected();
      }
    },

    /** 导出全部数据 */
    handleExportAll() {
      // 检查数据量限制
      if (this.total > 200) {
        this.$modal.msgError(`数据量过大，无法导出全部数据。当前查询结果 ${this.total} 条，最多支持导出 200 条单据。请缩小查询范围或使用批量导出功能。`);
        return;
      }

      const message = this.total > 0
        ? `是否确认导出所有单据数据？（共 ${this.total} 条记录，包含明细和追溯码信息）\n\n注意：\n• 为避免超时，系统已优化导出速度，每个药品最多包含3个追溯码\n• 系统已设置8分钟超时时间\n• 请勿关闭浏览器或刷新页面`
        : '是否确认导出所有单据数据？（包含明细和追溯码信息）\n\n注意：\n• 系统已设置8分钟超时时间\n• 请勿关闭浏览器或刷新页面';

      this.$modal.confirm(message).then(() => {
        this.$modal.loading("正在导出数据，请稍候...");
        this.download('wareHouse/list/export', {
          ...this.queryParams
        }, `单据数据_全部_${new Date().getTime()}.xlsx`, {
          timeout: 480000 // 5分钟超时
        });
      }).catch(() => {});
    },

    /** 导出选中数据 */
    handleExportSelected() {
      if (this.multiple) {
        this.$modal.msgWarning("请先选择要导出的单据");
        return;
      }

      if (this.ids.length === 0) {
        this.$modal.msgWarning("请先选择要导出的单据");
        return;
      }

      // 检查选中数量限制
      if (this.ids.length > 20) {
        this.$modal.msgError(`选中单据数量过多，无法导出。当前选中 ${this.ids.length} 个不同单据，最多支持选中导出 20 个单据。请分批选择导出。`);
        return;
      }

      const message = `是否确认导出选中的 ${this.ids.length} 个单据的数据？（包含明细和追溯码信息）\n\n注意：\n• 系统已自动去重相同单据号\n• 导出过程可能需要较长时间，请耐心等待\n• 系统已设置8分钟超时时间\n• 请勿关闭浏览器或刷新页面`;

      this.$modal.confirm(message).then(() => {
        this.$modal.loading("正在导出选中数据，请稍候...");
        this.download('wareHouse/list/exportSelected', {
          billsIDs: this.ids.join(',')
        }, `单据数据_选中${this.ids.length}个单据_${new Date().getTime()}.xlsx`, {
          timeout: 300000 // 5分钟超时
        });
      }).catch(() => {});
    },
    /** 单据类型改变事件 */
    handleBillsTypeChange(value) {
      this.queryParams.billsType = value;
    },

    /** 获取单据类型标签类型 */
    getBillsTypeTagType(billsType) {
      return this.billsTypeColorMap[billsType] || 'info';
    },


    /** 格式化日期时间 */
    formatDateTime(dateTime) {
      if (!dateTime) return '-';

      // 处理SQL Server的datetime格式：2025-03-19 15:02:21.9470000
      const date = new Date(dateTime);
      if (isNaN(date.getTime())) return dateTime;

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    /** 获取上传状态标签类型 */
    getUploadStateTagType(uploadState) {
      switch(uploadState) {
        case '0': return 'info';     // 未上传 - 灰色
        case '1': return 'success';  // 上传成功 - 绿色
        case '2': return 'danger';   // 上传失败 - 红色
        default: return 'info';
      }
    },

    /** 获取上传状态文本 */
    getUploadStateText(uploadState) {
      switch(uploadState) {
        case '0': return '未上传';
        case '1': return '上传成功';
        case '2': return '上传失败';
        default: return '-';
      }
    },

    /** 上传按钮操作 */
    handleUpload(row) {
      this.currentRow = row;
      this.uploadForm.billsID = row.billsID;
      this.selectedInstitution = null;
      this.uploadForm.institutionId = '';
      this.uploadForm.institutionName = '';
      this.medicalInstitutionDialogVisible = true;
    },

    /** 获取医疗机构列表 */
    getMedicalInstitutions() {
      listMedicalInstitutions().then(response => {
        this.medicalInstitutionsList = response.rows || [];
      }).catch(error => {
        console.error('获取医疗机构数据失败:', error);
        this.$modal.msgError("获取医疗机构数据失败");
      });
    },

    /** 医疗机构选择改变事件 */
    handleInstitutionChange(val) {
      if (val) {
        const selectedInstitution = this.medicalInstitutionsList.find(item => item.institutionId === val);
        if (selectedInstitution) {
          this.uploadForm.institutionId = selectedInstitution.institutionId;
          this.uploadForm.institutionName = selectedInstitution.institutionName;
        }
      } else {
        this.uploadForm.institutionId = '';
        this.uploadForm.institutionName = '';
      }
    },

    /** 确认上传 */
    confirmUpload() {
      if (!this.uploadForm.institutionId) {
        this.$modal.msgWarning("请选择医疗机构");
        return;
      }

      this.$modal.confirm('确认要上传单据"' + this.uploadForm.billsID + '"到易联云码平台吗？').then(() => {
        this.$modal.loading("正在上传中，请稍候...");

        // 将医疗机构信息一起传递给后端
        const institutionData = {
          institutionId: this.uploadForm.institutionId,
          institutionName: this.uploadForm.institutionName
        };

        uploadBills(this.uploadForm.billsID, institutionData).then(response => {
          this.$modal.closeLoading();
          this.$modal.msgSuccess("上传成功");
          this.medicalInstitutionDialogVisible = false;
          this.getList();
        }).catch(error => {
          this.$modal.closeLoading();
          this.$modal.msgError("上传失败：" + (error.msg || "未知错误"));
        });
      }).catch(() => {});
    },

    /** 批次号维护按钮操作 */
    handleBatchNumberMaintenance(row) {
      console.log('批次维护按钮点击，行数据:', row);
      console.log('当前Vue实例:', this);
      console.log('当前detailList:', this.detailList);

      this.currentBillsInfo = row;
      this.batchNumberDialogVisible = true;

      // 重置测试输入框
      this.testInput = '';
      this.testInput2 = '';

      this.getDetailList(row.billsID);
    },

    /** 获取明细列表 */
    getDetailList(billsID) {
      console.log('开始获取明细列表，单据号:', billsID);
      this.detailLoading = true;
      this.detailList = [];

      getBillsDetailList(billsID).then(response => {
        console.log('API返回的明细数据:', response);
        const rawDetailList = response.rows || [];
        console.log('原始明细列表:', rawDetailList);

        // 初始化可编辑字段，自动带入原有值，处理null/'null'/undefined
        this.detailList = rawDetailList.map(item => {
          // 批次号
          let batch = item.batchNumber || item.drugBatchNo || '';
          if (batch === null || batch === undefined || batch === 'null') batch = '';
          // 生产日期
          let pd = item.productionDate || item.drugPD || '';
          if (pd === null || pd === undefined || pd === 'null') pd = '';
          // 有效期
          let exp = item.validityPeriod || item.drugExp || '';
          if (exp === null || exp === undefined || exp === 'null') exp = '';
          return {
            ...item,
            drugName: item.drugName || '',
            batchNumber: batch,
            productionDate: pd ? pd.substr(0, 10) : '',
            validityPeriod: exp ? exp.substr(0, 10) : '',
            remark: item.remark || item.remarks || ''
          };
        });

        this.detailLoading = false;
        console.log('最终明细列表:', this.detailList);

        // 使用$nextTick确保DOM更新完成
        this.$nextTick(() => {
          console.log('DOM更新完成，detailList长度:', this.detailList.length);
          // 强制更新表格
          this.$forceUpdate();
        });
      }).catch(error => {
        console.error('获取明细数据失败:', error);
        this.detailLoading = false;
        this.$modal.msgError("获取明细数据失败");
      });
    },

    /** 确认批次号更新 */
    confirmBatchNumberUpdate() {
      // 检查是否有修改的数据
      const modifiedItems = this.detailList.filter(item =>
        item.batchNumber && item.batchNumber.trim() !== ''
      );

      if (modifiedItems.length === 0) {
        this.$modal.msgWarning("请至少填写一个批次号");
        return;
      }

      // 构建更新数据
      const updateData = {
        billsID: this.currentBillsInfo.billsID,
        details: modifiedItems.map(item => ({
          drugID: item.drugID,
          drugName: item.drugName,
          batchNumber: item.batchNumber,
          drugPD: item.productionDate,
          drugExp: item.validityPeriod,
          remark: item.remark
        }))
      };

      this.updateLoading = true;

      updateDetailBatchNumber(updateData).then(response => {
        this.updateLoading = false;
        this.batchNumberDialogVisible = false;
        this.$modal.msgSuccess("批次号维护成功");
        this.getList(); // 刷新主列表
      }).catch(error => {
        this.updateLoading = false;
        this.$modal.msgError("批次号维护失败：" + (error.msg || "未知错误"));
      });
    },

    /** 处理备注输入 */
    handleRemarkInput(index, value) {
      console.log('备注输入:', index, value);
      this.$set(this.detailList[index], 'remark', value);
    }
  }
};
</script>
